﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace LogWatcherRSS
{
    class EventLogRSS
    {
        //class variables:
        private EventLog m_EventLog = null;    //Event log to monitor

        bool m_ToDebug = false;
        string m_DebugFileName = "";

        string m_RSSFeedsFolder = "";
        string m_RSSFeedFileName = "";

        string m_EventLogName = "";        //actual name of Event log to monitor

        string m_FilterEventSource = "";        //filter by Source name
        ArrayList m_FilterEventSourceList = new ArrayList();

        string m_FilterEventType = "";        //filter by event type
        ArrayList m_FilterEventTypeList = new ArrayList();

        //how many records before creating a new RSS file
        int m_RecordsToPull = 250;

        int m_CurrentRecordCount = 0;

        //machine where Event Log Watcher service is running
        string m_LocalIP = System.Net.Dns.GetHostName();


        public EventLogRSS(string logName, bool toDebug, string debugFileName, string rssFeedsPath, string filterEventSource, string filterEventType, int recordsToPull)
        {
            m_EventLogName = logName;
            m_ToDebug = toDebug;
            m_DebugFileName = debugFileName;
            m_RSSFeedsFolder = rssFeedsPath;
            //construct RSS Feed File Name:
            m_RSSFeedFileName = Path.Combine(m_RSSFeedsFolder, m_EventLogName + "_eventlog_rss.xml");

            //filters
            m_FilterEventSource = filterEventSource;
            m_FilterEventType = filterEventType;

            if (m_FilterEventSource != String.Empty)
            { 
                m_FilterEventSourceList.AddRange(m_FilterEventSource.Split(',')); 
            }

            if (m_FilterEventType != String.Empty)
            { 
                m_FilterEventTypeList.AddRange(m_FilterEventType.Split(',')); 
            }


            //how many records in a RSS file, before a new file is created
            m_RecordsToPull = recordsToPull;

            //initialize log...
            m_EventLog = new EventLog(logName);
            m_EventLog.EntryWritten += new EntryWrittenEventHandler(EventLog_OnEntryWritten);
            m_EventLog.EnableRaisingEvents = true;

            //create new RSS file
            StartRSSFeed();
        }
        
        public void EventLog_OnEntryWritten(object source, EntryWrittenEventArgs e)
        {
            try
            {
                if (m_ToDebug)
                {
                    //or use m_EventLogName
                    string eventLogName = ((EventLog)source).LogDisplayName;

                    AddDebugMessage(eventLogName + " - " + e.Entry.Source + ":" + e.Entry.Message);
                }
                //filter it?
                if ((m_FilterEventSource == String.Empty || m_FilterEventSourceList.Contains(e.Entry.Source)) && m_FilterEventTypeList.Contains(e.Entry.EntryType.ToString()))
                {
                    if (m_CurrentRecordCount > m_RecordsToPull)
                    {
                        StartRSSFeed();
                    }
                    //create entry in RSS file...
                    AddEntryToRSSFeed((EventLogEntry)e.Entry);
                    m_CurrentRecordCount += 1;
                }
                else
                {
                    if (m_ToDebug)
                    { 
                        AddDebugMessage("not in filter --> " + e.Entry.Source + ":" + e.Entry.EntryType.ToString());
                    }
                }
            }
            catch (Exception ex_on_entry_written)
            {
                //oh-ho...
                AddDebugMessage("Failed to EventLog_OnEntryWritten() for [" + m_EventLog + "] event log\n" + ex_on_entry_written.Message);
            }
        }

        public void AddEntryToRSSFeed(EventLogEntry entry)
        {
            try
            {
                XmlDocument rssFeedXMLDoc = new XmlDocument();
                rssFeedXMLDoc.Load(m_RSSFeedFileName);
                XmlElement rssFeedItemElement =
                rssFeedXMLDoc.CreateElement("item");
                //
                rssFeedItemElement.InnerXml =
                "<title></title><link></link><description></description><pubdate /></pubdate />";
                rssFeedItemElement["title"].InnerText =
                entry.Source + "-" + entry.EntryType.ToString();
                rssFeedItemElement["link"].InnerText = "";
                rssFeedItemElement["description"].InnerText = entry.Message;
                rssFeedItemElement["pubDate"].InnerText =
                entry.TimeGenerated.ToString("r");

                rssFeedXMLDoc.DocumentElement.SelectNodes
                ("/rss/channel")[0].AppendChild(rssFeedItemElement);
                rssFeedXMLDoc.Save(m_RSSFeedFileName);
            }

            catch (Exception ex_add_entry_to_rss_fee)
            {
                AddDebugMessage("Failed to AddEntryToRSSFeed() for [" + m_EventLog + "] event log\n" + ex_add_entry_to_rss_fee.Message);
            }
        }

        private void AddDebugMessage(string message)
        {

        }

        private void StartRSSFeed()
        {

        }
    }
}
